// repositories/db.go
package repositories

import (
	"log"
	"myapi/config"
	"myapi/models"

	"gorm.io/driver/mysql"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

var DB *gorm.DB

// InitDB 初始化数据库连接
func InitDB(config *config.Config) {
	var err error
	var dialector gorm.Dialector

	switch config.DBDriver {
	case "mysql":
		dialector = mysql.Open(config.GetDSN())
	case "sqlite":
		dialector = sqlite.Open(config.GetDSN())
	default:
		log.Fatalf("Unsupported database driver: %s", config.DBDriver)
	}

	DB, err = gorm.Open(dialector, &gorm.Config{})
	if err != nil {
		log.Fatalf("Failed to connect to database: %v", err)
	}

	// 自动迁移模型
	err = DB.AutoMigrate(&models.User{}, &models.Subject{}, &models.Score{}, &models.Paper{}, &models.PaperReview{}, &models.Order{}, &models.OrderItem{})
	if err != nil {
		log.Fatalf("数据库连接失败: %v", err)
	}
	log.Println("数据库连接成功")
}
